const net = require('net');
const color = require('chalk');
let clients = [];
let server = net.createServer();
server.on('connection', (socket) => {
  console.log(color.hex('#00ff19')(`get connection ${socket.remoteAddress}:${socket.remotePort}`));
  socket.write(color.hex('#ffd600')(`server: hi~${socket.remoteAddress}:${socket.remotePort}\nplease enter the key!`));
  socket.lock = true;
  socket.un = undefined;
  socket.on('data', (data) => {
    if (socket.lock) {
      if (data.toString() === '^528491$') {
        socket.lock = false;
        socket.write(color.hex('#ffd600')('server: enter a name'));
      } else {
        socket.write(color.hex('#ffd600')('server: key error,please input again!'));
      }
    } else {
      if (socket.un) {
        socket.write(color.hex('#00ff48')(`[${new Date().toJSON()}] you say: ${data}`));
        broadcast(color.hex('#00ffff')(`[${new Date().toJSON()}] ${socket.un} say: ${data}`), socket);
      } else {
        socket.un = data.toString();
        socket.write(color.hex('#fffd00')(`server: welcome ${socket.un}\nnow,you can write some message and send`));
        broadcast(color.hex('#fffd00')(`[${new Date().toJSON()}] server: ${socket.un} join`),socket);
      }
    }
  });
  socket.on('end', () => {
    clients.splice(clients.indexOf(socket), 1);
    if (socket.lock === false && socket.un !== undefined) {
      broadcast(color.hex('#00ffff')(`[${new Date().toJSON()}] server: ${socket.un} leave`), socket);
    }
  })
  socket.on('error', () => {
    clients.splice(clients.indexOf(socket), 1);
    if (socket.lock === false && socket.un !== undefined) {
      broadcast(color.hex('#00ffff')(`[${new Date().toJSON()}] server: ${socket.un} leave`), socket);
    }
  })
  clients.push(socket);
});

function broadcast(message, socket) {
  let cleanup = [];
  for (let i = 0; i < clients.length; i++) {
    if (clients[i] !== socket && clients[i].un !== undefined && !clients[i].lock) {
      if (clients[i].writable) {
        clients[i].write(message);
      } else {
        cleanup.push(clients[i]);
      }
    }
  }
  for (let i = 0; i < cleanup.length; i++) {
    clients.splice(clients.indexOf(cleanup[i]), 1);
  }
}

server.listen(1024, '0.0.0.0', () => {
  console.log('server start');
});